package com.cyh.blog.controller;

import com.cyh.blog.util.Result;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.UnauthorizedException;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;

@Controller
@RequestMapping(value = "/passport")
public class PassportSigninController {

    @PostMapping("/signin")
    @ResponseBody
    public Result login(String username, String password , boolean rememberMe, HttpSession session, ModelMap map){
        //...验证码

        UsernamePasswordToken token = new UsernamePasswordToken(username,
                password, rememberMe);

        Subject subject = SecurityUtils.getSubject();
        String error = null;
        try {
            subject.login(token);
        }catch (IncorrectCredentialsException e) {
            error = "登录密码错误.";
        } catch (ExcessiveAttemptsException e) {
            error = e.getMessage();
        } catch (LockedAccountException e) {
            error = "帐号已被锁定.";
        } catch (DisabledAccountException e) {
            error = "帐号已被禁用.";
        } catch (ExpiredCredentialsException e) {
            error = "帐号已过期.";
        } catch (UnknownAccountException e) {
            error = "帐号不存在";
        } catch (UnauthorizedException e) {
            error = "您没有得到相应的授权！";
        } catch (AccountException e){
            error = e.getMessage();
        }
        session.setAttribute("username",username);
        if (StringUtils.isEmpty(error)){
            return Result.success("登录成功");
        }else{
            return Result.error(error);
        }
    }


    @GetMapping("/logout")
    public String logout() {
       // redirectAttributes.addAttribute("message", "你已退出");
        SecurityUtils.getSubject().logout();
        return "redirect:/login";
    }
}
